<script lang="ts" setup>
  import { reactive, ref, watch, computed, onMounted } from 'vue';
  import { FormInstance, message } from 'ant-design-vue';
  import { useAuthStore } from '@/plugins';
  import http from '@/store/http';
  import { Response } from '@/types';

  const { useAuth } = useAuthStore();

  const columns = [
    {
      title: '角色',
      dataIndex: 'name',
    },
    {
      title: '角色标签',
      dataIndex: 'title',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
    },
    {
      title: '创建时间',
      dataIndex: 'createUser',
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
    },
    {
      title: '创建时间',
      dataIndex: 'updateUser',
    },
    {
      width: 140,
      title: '操作',
      align: 'center',
      dataIndex: 'operation',
    },
  ];

  const showForm = ref(false);

  interface Role {
    id?: number
    name: string,
    title: string
  }

  const roleList = ref<Role[]>();

  const formData = reactive<Role>({
    id: undefined,
    name: '',
    title: undefined,
  });

  const updateRole = (role: Role) => {
    form.value.validateFields().then(() => {
      http.request<String, Response<String>>('/api/role', 'put_json', formData).then(res => {
        const { code, msg } = res;
        if (code !== 200) {
          message.error(msg);
          return;
        }
        message.success(msg);
        showForm.value = false;
        getRoleList();
      });
    });
  };

  const addRole = (role: Role) => {
    form.value.validateFields().then(() => {
      http.request<String, Response<String>>('/api/role', 'post_json', formData).then(res => {
        const { code, msg } = res;
        if (code !== 200) {
          message.error(msg);
          return;
        }
        message.success(msg);
        showForm.value = false;
        getRoleList();
      });
    });
  };

  const form = ref<FormInstance>();

  const loading = ref(false);

  function submit() {
    loading.value = true;
    form.value
      ?.validate()
      .then(() => {
        formData.id ? updateRole(formData) : addRole(formData);
        showForm.value = false;
      })
      .finally(() => {
        loading.value = false;
      });
  }

  const title = ref('新增角色');

  const edit = useAuth('admin', function(record: Role) {
    form.value?.resetFields();
    formData.id = record.id;
    formData.name = record.name;
    formData.title = record.title;
    showForm.value = true;
    title.value = '编辑角色';
  });

  function add() {
    form.value?.resetFields();
    formData.id = undefined;
    formData.name = '';
    formData.title = undefined;
    showForm.value = true;
    title.value = '新增角色';
  }

  const removeRole = (role: Role) => {
    http.request<String, Response<String>>('/api/role/' + role.id, 'delete').then(res => {
      const { code, msg } = res;
      if (code !== 200) {
        message.error(msg);
        return;
      }
      message.success(msg);
      showForm.value = false;
      getRoleList();
    });
  };

  onMounted(() => {
    getRoleList();
  });

  const getRoleList = () => {
    http.request<Role[], Response<Role[]>>('/api/role', 'get').then(res => {
      const { code, data } = res;
      if (code === 200) {
        roleList.value = data;
      }
    });
  };

</script>
<template>
  <div class="authority">
    <a-table
      rowKey="id"
      :columns="columns"
      :dataSource="roleList"
      :pagination="{ pageSize: 20, current: 1, total: 10 }"
    >
      <template #title>
        <div class="flex justify-between">
          角色信息
          <div class="flex">
            <a-button type="primary" @click="add">
              <template #icon>
                <PlusOutlined />
              </template>
              新增
            </a-button>
          </div>
        </div>
      </template>
      <template #bodyCell="{ text, record, index, column }">
        <template v-if="column.dataIndex === 'operation'">
          <a-button class="text-xs" type="primary" size="small" @click="edit(record)">编辑</a-button>
          <a-popconfirm title="确认删除？" @confirm="removeRole(record)">
            <a-button class="text-xs ml-base" danger size="small">删除</a-button>
          </a-popconfirm>
        </template>
        <template v-else-if="column.dataIndex === 'icon'">
          <component :is="record.icon" />
        </template>
      </template>
    </a-table>
    <a-modal :okButtonProps="{ loading }" width="540px" v-model:visible="showForm" :title="title" @ok="submit">
      <a-form ref="form" :model="formData" :labelCol="{ span: 5 }" :wrapperCol="{ span: 16, offset: 1 }">
        <a-form-item required name="name" label="角色">
          <a-input v-model:value="formData.name" />
        </a-form-item>
        <a-form-item required name="title" label="角色标题">
          <a-input v-model:value="formData.title" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>
